package com.xcm.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by YPZS on 17/11/27.
 */
public class FileUtils {

	/**
	 * 读取文件
	 *
	 * @param path
	 * @return
	 */
	public static String readFile(String path) {
		StringBuffer laststr = new StringBuffer("");
		File file = new File(path);// 打开文件
		BufferedReader reader = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				laststr.append(tempString);
			}
			reader.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException el) {
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException el) {
				}
			}
		}
		return laststr.toString();
	}

	/**
	 * 保存文件
	 *
	 * @param url
	 * @param name
	 * @param retry
	 */
	public static void saveUrlAs(String url, String name, int retry) throws UnsupportedEncodingException {
		//System.out.println("fileName---->"+filePath);
		//创建不同的文件夹目录
		if (retry <= 0) {
			return;
		}

		//json文件存放目录
		String jsonFilePath = PropertyFileUtils.getPropertyValueByKey("application-dev", "custom.json-file-save-path");
		File file = new File(jsonFilePath);
		//判断文件夹是否存在
		if (!file.exists()) {
			//如果文件夹不存在，则创建新的的文件夹
			file.mkdirs();
		}
		FileOutputStream fileOut = null;
		HttpURLConnection conn = null;
		InputStream inputStream = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			// 建立链接
			URL httpUrl = new URL(url);
			conn = (HttpURLConnection) httpUrl.openConnection();
			//以Post方式提交表单，默认get方式
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			// post方式不能使用缓存
			conn.setUseCaches(false);
			//连接指定的资源
			conn.connect();
			//获取网络输入流
			inputStream = conn.getInputStream();
			bis = new BufferedInputStream(inputStream);
			//判断文件的保存路径后面是否以/结尾
			if (!jsonFilePath.endsWith("/")) {

				jsonFilePath += "/";

			}
			//写入到文件（注意文件保存路径的后面一定要加上文件的名称）
			fileOut = new FileOutputStream(jsonFilePath + name);
			bos = new BufferedOutputStream(fileOut);

			byte[] buf = new byte[1024];
			int length = bis.read(buf);
			//保存文件
			while (length != -1) {
				bos.write(buf, 0, length);
				length = bis.read(buf);
			}
		} catch (Exception e) {
			e.printStackTrace();
			saveUrlAs(url, name, retry - 1);
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
				if (bis != null) {
					bis.close();
				}
				if (fileOut != null) {
					fileOut.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		//return file;
	}

	/**
	 * MultipartFile转化为File
	 *
	 * @param multipartFile MultipartFile
	 * @return File
	 * @throws IOException
	 */
	public static File multipartFileConvertFile(MultipartFile multipartFile) throws IOException {
		if (multipartFile == null) {
			throw new NullPointerException("文件不能为空");
		}
		File file = new File(multipartFile.getOriginalFilename());
		file.createNewFile();
		//自动关闭流
		try (FileOutputStream fos = new FileOutputStream(file)) {
			fos.write(multipartFile.getBytes());
		}
		return file;
	}

	/**
	 * 获取Apk文件MD5值
	 *
	 * @param filePath String
	 * @return String
	 */
	public static String getFileMD5(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			try {
				MessageDigest messageDigest = MessageDigest.getInstance("MD5");
				InputStream in = new FileInputStream(file);
				byte[] cache = new byte[1024];
				int nRead = 0;
				while ((nRead = in.read(cache)) != -1) {
					messageDigest.update(cache, 0, nRead);
				}
				in.close();
				byte data[] = messageDigest.digest();
				return byteToHex(data);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * 获取Apk文件MD5值
	 *
	 * @param apkFile File
	 * @return String
	 */
	public static String getApkFileMD5(File apkFile) {
		String md5 = "";
		if (apkFile.exists() && apkFile.isFile()) {
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				InputStream in = new FileInputStream(apkFile);
				byte[] buffer = new byte[1024];
				int read = 0;
				while ((read = in.read(buffer)) != -1) {
					md.update(buffer, 0, read);
				}
				in.close();
				byte data[] = md.digest();
				md5 = byteToHex(data);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return md5;
	}

	/**
	 * byte转化为16进制字符串
	 *
	 * @param bytes byte[]
	 * @return String
	 */
	protected static String byteToHex(byte[] bytes) {
		char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f'};
		StringBuffer stringbuffer = new StringBuffer(2 * bytes.length);
		for (byte b : bytes) {
			char c0 = hexDigits[b >>> 4 & 0xf];
			char c1 = hexDigits[b & 0xf];
			stringbuffer.append(c0);
			stringbuffer.append(c1);
		}
		return stringbuffer.toString();
	}

	/**
	 * TODO 读取文件(导入JSON文件发布广告测试)
	 *
	 * @param multipartFile
	 * @return
	 */
	public static String readFile(MultipartFile multipartFile) throws IOException {
		StringBuffer laststr = new StringBuffer("");
//		File file = multipartFileConvertFile(multipartFile);
        File file = new File(multipartFile.getOriginalFilename());
        //自动关闭流
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
		BufferedReader reader = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				laststr.append(tempString);
			}
			reader.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException el) {
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException el) {
				}
			}
			if(null != file){
				file.delete();
			}
		}
		return laststr.toString();
	}

	/**
	 * 从网路地址中获取文件
	 *
	 * @param downloadStie 下载地址
	 * @param dest         文件存储全路径
	 * @throws IOException
	 */
	public static void downloadFileFromURL(String downloadStie, String dest) throws IOException {
		if (StringUtils.isBlank(downloadStie) || StringUtils.isBlank(dest)) {
			throw new NullPointerException("");
		}
		URL url = new URL(downloadStie);
		try (ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(dest)) {
			fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
		}
	}

}
